package com.ldg.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ld.pojo.PayAsyncVo;
import com.ld.pojo.TbPayLog;
import com.ld.utils.AlipayTemplate;
import com.ldg.order.entity.TbOrder;
import com.ldg.order.service.OrderService;
import com.ldg.order.service.PayLogService;
import com.ldg.order.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

/**
 * @Author: Liudao
 * @Date: 2022-10-20-17:50
 * @Description:
 */
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private PayLogService payLogService;

    @Override
    @Transactional
    public String payNotify(PayAsyncVo vo, HashMap<String, String> params) throws AlipayApiException {
        //验签
        boolean b = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名（注意不要调错方法）
        if (b){
            if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
                //第一部分，修改支付日志
                //根据支付宝传回的交易号查询支付日志
                TbPayLog payLog = payLogService.findPayLogByTradeNo(vo.getOut_trade_no());
                //支付日志存在就修改
                if (payLog != null){
                    //设置支付时间
                    payLog.setPayTime(new Date());
                    //设置交易号
                    payLog.setTransactionId(vo.getTrade_no());
                    //修改支付状态值（0：未付款，1：已付款）
                    payLog.setTradeState("1");
                    //保存到数据库
                    payLogService.updatePayLog(payLog);

                    //第二部分，修改订单
                    //得到订单id列表
                    String[] ids = payLog.getOrderList().split(",");
                    //遍历并修改订单
                    for (String id : ids) {
                        TbOrder order = orderService.findOrdersById(id);
                        order.setStatus("2");       //1是未支付，2是已支付
                        orderService.update(order);
                    }
                    System.out.println("成功");
                    return "success";
                }
            }
        }
        System.out.println("失败");
        return "fail";
    }
}
